import base64
import hashlib
import json

from cryptography.fernet import Fernet
from getmac import get_mac_address as gma

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance
class privateKeyData(Singleton):

    def __init__(self):
        if hasattr(self, '_initialized'):
            return
        self._initialized = True
        self.key = "dasdasfasf"
        self.fernet = Fernet("b8jjOdh5aTh5ozVneKPEHMIyDTbg0vId3QJTo8Q0uek=")

    # def jiaMi(self,data):
    #     encrypted_text = ""
    #     key_length = len(self.key)
    #     for i, char in enumerate(data):
    #         encrypted_char = chr((ord(char) + ord(self.key[i % key_length])) % 256)
    #         encrypted_text += encrypted_char
    #     return base64.b64encode(encrypted_text.encode('latin1')).decode('latin1')
    #
    # def jieMi(self, data: str):
    #     encrypted_text = base64.b64decode(data).decode('latin1')
    #     decrypted_text = ""
    #     key_length = len(self.key)
    #     for i, char in enumerate(encrypted_text):
    #         decrypted_char = chr((ord(char) - ord(self.key[i % key_length])) % 256)
    #         decrypted_text += decrypted_char
    #     return decrypted_text
    def jiaMi(self,data:str):
        # 解密数据
        encrypted_code = self.fernet.encrypt(data.encode())
        return encrypted_code.decode()

    def jieMi(self,data:str):
        # 解密数据
        decrypted_data = self.fernet.decrypt(data)
        return decrypted_data.decode()


    def machineCode(self):
        BOARD = gma()
        return hashlib.md5(BOARD.encode(encoding='UTF-8')).hexdigest()

# machineCode = privateKeyData().machineCode()
# data ={
#     "privateKey":machineCode,
#     "qty":999,
#     "indate":"2050-09-08"
# }
# aaa1 = privateKeyData().jiaMi(data=json.dumps(data,ensure_ascii=False))
# print("加密数据",aaa1)
# aaa2 = privateKeyData().jieMi(aaa1)
# print("解密数据",aaa2)

# aaa1 = privateKeyData().jiaMi(data=json.dumps(data,ensure_ascii=False))
# print("加密数据",aaa1)
# aaa2 = privateKeyData().jieMi(aaa1)
# print("解密数据",aaa2)
